package com.hdu.dwh.validators;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hdu.dwh.dtos.model_dtos.ModelCreateDto;
import com.hdu.dwh.pojos.model_pojos.MetaTable;
import com.hdu.dwh.pojos.source_access_pojos.DataWarehouseTable;
import com.hdu.dwh.service.DataWarehouseTableService;

@Component
public class ModelCreateDtoValidator implements Validator {
    
    private final MetaTableValidator metaTableValidator;

    @Autowired
    private DataWarehouseTableService dwhTableService;
    
    
    public ModelCreateDtoValidator(MetaTableValidator metaTableValidator) {
        this.metaTableValidator = metaTableValidator;
    }
    
    @Override
    public boolean supports(Class<?> clazz) {
        return ModelCreateDto.class.equals(clazz);
    }
    
    @Override
    public void validate(Object target, Errors errors) {
        ModelCreateDto dto = (ModelCreateDto) target;
        
        // 验证factTable字段
        if (dto.getFactTable() != null) {
            try {
                errors.pushNestedPath("factTable");
                ValidationUtils.invokeValidator(metaTableValidator, dto.getFactTable(), errors);
            } finally {
                errors.popNestedPath();
            }
        }
        
        // 验证dimensionTables
        if (dto.getDimensionTables() != null) {
            int i = 0;
            for (MetaTable table : dto.getDimensionTables()) {
                try {
                    errors.pushNestedPath("dimensionTables[" + i + "]");
                    ValidationUtils.invokeValidator(metaTableValidator, table, errors);
                } finally {
                    errors.popNestedPath();
                }
                i++;
            }
        }

        // 验证模型名称在同一数据库下是否重复
        Long databaseId = dto.getDatabaseId();
        String modelName = dto.getName();
        if (databaseId != null && modelName != null) {

            // 需要根据数据库ID和模型名称判断是否存在
            QueryWrapper<DataWarehouseTable> queryWrapper =
                new QueryWrapper<>();
            queryWrapper.eq("database_id", databaseId).eq("table_name", modelName);
            boolean exists = dwhTableService.exists(queryWrapper);
            if (exists) {
                errors.rejectValue("name", "ModelCreateDto.name.duplicate", "模型名称在该数据库下已存在");
            }
        }

    }
}